{% extends 'base.html' %}

{% block title %}时间戳转换器{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">时间戳转换器</h1>
        <p class="text-gray-600">在时间戳和日期字符串之间轻松转换</p>
    </div>

    <div class="flex flex-col lg:flex-row gap-8">
        <!-- 侧边栏工具列表 -->
        <div class="w-full lg:w-1/4">
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-bold mb-6 text-gray-800">开发工具</h2>
                <ul class="space-y-3">
                    <li>
                        <a href="{{ url_for('dev_tools.json_formatter') }}" class="flex items-center text-gray-600 hover:text-purple-600">
                            <div class="w-8 text-center">
                                <i class="fas fa-code-branch"></i>
                            </div>
                            <span>JSON格式化</span>
                        </a>
                    </li>
                    <li>
                        <a href="{{ url_for('dev_tools.code_formatter') }}" class="flex items-center text-gray-600 hover:text-purple-600">
                            <div class="w-8 text-center">
                                <i class="fas fa-code"></i>
                            </div>
                            <span>代码格式化</span>
                        </a>
                    </li>
                    <li>
                        <a href="{{ url_for('dev_tools.regex_tester') }}" class="flex items-center text-gray-600 hover:text-purple-600">
                            <div class="w-8 text-center">
                                <i class="fas fa-search"></i>
                            </div>
                            <span>正则表达式测试</span>
                        </a>
                    </li>
                    <li>
                        <a href="{{ url_for('dev_tools.timestamp_converter') }}" class="flex items-center text-purple-600 font-medium">
                            <div class="w-8 text-center">
                                <i class="fas fa-clock"></i>
                            </div>
                            <span>时间戳转换</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="w-full lg:w-3/4">
            <div class="bg-white rounded-lg shadow-md p-6">
                <!-- 转换类型选项卡 -->
                <div class="mb-6 border-b border-gray-200">
                    <div class="flex -mb-px">
                        <button id="timestamp-to-date-tab" class="px-4 py-2 font-medium text-purple-600 border-b-2 border-purple-600 mr-2 focus:outline-none">
                            时间戳转日期
                        </button>
                        <button id="date-to-timestamp-tab" class="px-4 py-2 font-medium text-gray-500 hover:text-gray-700 focus:outline-none">
                            日期转时间戳
                        </button>
                    </div>
                </div>

                <!-- 时间戳转日期内容 -->
                <div id="timestamp-to-date" class="tab-content">
                    <form id="timestamp-form" class="mb-6">
                        <div class="mb-4">
                            <label for="timestamp-input" class="block text-gray-700 font-medium mb-2">时间戳</label>
                            <input type="text" id="timestamp-input" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500" 
                                placeholder="请输入Unix时间戳，例如：1650000000">
                            <p class="mt-1 text-sm text-gray-500">支持秒级时间戳（10位）和毫秒级时间戳（13位）</p>
                        </div>
                        
                        <div class="mb-4">
                            <label for="timestamp-format" class="block text-gray-700 font-medium mb-2">日期格式</label>
                            <select id="timestamp-format" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                <option value="%Y-%m-%d %H:%M:%S">YYYY-MM-DD HH:MM:SS (默认)</option>
                                <option value="%Y/%m/%d %H:%M:%S">YYYY/MM/DD HH:MM:SS</option>
                                <option value="%Y年%m月%d日 %H时%M分%S秒">YYYY年MM月DD日 HH时MM分SS秒</option>
                                <option value="%Y-%m-%d">YYYY-MM-DD</option>
                                <option value="%H:%M:%S">HH:MM:SS</option>
                                <option value="custom">自定义...</option>
                            </select>
                        </div>
                        
                        <div id="custom-timestamp-format-group" class="mb-4 hidden">
                            <label for="custom-timestamp-format" class="block text-gray-700 font-medium mb-2">自定义格式</label>
                            <input type="text" id="custom-timestamp-format" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500" 
                                placeholder="%Y-%m-%d %H:%M:%S">
                            <p class="mt-1 text-sm text-gray-500">
                                <a href="https://docs.python.org/zh-cn/3/library/datetime.html#strftime-and-strptime-format-codes" 
                                    target="_blank" class="text-blue-600 hover:underline">格式代码参考</a>
                            </p>
                        </div>
                        
                        <div class="flex space-x-2">
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                                <i class="fas fa-exchange-alt mr-2"></i>转换
                            </button>
                            <button type="button" id="current-timestamp" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
                                <i class="fas fa-clock mr-2"></i>当前时间戳
                            </button>
                        </div>
                    </form>
                    
                    <!-- 加载指示器 -->
                    <div id="loading-indicator-timestamp" class="hidden">
                        <div class="flex justify-center items-center mb-4">
                            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                        </div>
                        <p class="text-center text-gray-600 text-sm">正在处理中...</p>
                    </div>
                    
                    <!-- 结果区域 -->
                    <div id="timestamp-result-container" class="hidden">
                        <div class="border-t border-gray-200 pt-6">
                            <h3 class="text-lg font-bold text-gray-800 mb-3">转换结果</h3>
                            <div class="bg-gray-50 rounded-md p-4 border border-gray-300">
                                <div class="flex justify-between items-center">
                                    <span id="date-result" class="font-mono"></span>
                                    <button class="copy-btn text-gray-500 hover:text-blue-600" data-target="date-result">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="mt-4">
                                <h4 class="font-medium text-gray-700 mb-2">其他格式</h4>
                                <div class="bg-gray-50 p-3 rounded border border-gray-200 text-sm">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                                        <div>
                                            <span class="text-gray-500">ISO8601:</span> 
                                            <span id="iso-result" class="font-mono"></span>
                                        </div>
                                        <div>
                                            <span class="text-gray-500">本地时间:</span> 
                                            <span id="local-time-result" class="font-mono"></span>
                                        </div>
                                        <div>
                                            <span class="text-gray-500">UTC时间:</span> 
                                            <span id="utc-time-result" class="font-mono"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 日期转时间戳内容 -->
                <div id="date-to-timestamp" class="tab-content hidden">
                    <form id="date-form" class="mb-6">
                        <div class="mb-4">
                            <label for="date-input" class="block text-gray-700 font-medium mb-2">日期时间</label>
                            <input type="text" id="date-input" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500" 
                                placeholder="请输入日期时间，例如：2022-04-15 12:00:00">
                        </div>
                        
                        <div class="mb-4">
                            <label for="date-format" class="block text-gray-700 font-medium mb-2">日期格式</label>
                            <select id="date-format" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                <option value="%Y-%m-%d %H:%M:%S">YYYY-MM-DD HH:MM:SS (默认)</option>
                                <option value="%Y/%m/%d %H:%M:%S">YYYY/MM/DD HH:MM:SS</option>
                                <option value="%Y年%m月%d日 %H时%M分%S秒">YYYY年MM月DD日 HH时MM分SS秒</option>
                                <option value="%Y-%m-%d">YYYY-MM-DD</option>
                                <option value="custom">自定义...</option>
                            </select>
                        </div>
                        
                        <div id="custom-date-format-group" class="mb-4 hidden">
                            <label for="custom-date-format" class="block text-gray-700 font-medium mb-2">自定义格式</label>
                            <input type="text" id="custom-date-format" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500" 
                                placeholder="%Y-%m-%d %H:%M:%S">
                            <p class="mt-1 text-sm text-gray-500">
                                <a href="https://docs.python.org/zh-cn/3/library/datetime.html#strftime-and-strptime-format-codes" 
                                    target="_blank" class="text-blue-600 hover:underline">格式代码参考</a>
                            </p>
                        </div>
                        
                        <div class="flex space-x-2">
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                                <i class="fas fa-exchange-alt mr-2"></i>转换
                            </button>
                            <button type="button" id="current-date" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
                                <i class="fas fa-calendar-alt mr-2"></i>当前日期时间
                            </button>
                        </div>
                    </form>
                    
                    <!-- 加载指示器 -->
                    <div id="loading-indicator-date" class="hidden">
                        <div class="flex justify-center items-center mb-4">
                            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                        </div>
                        <p class="text-center text-gray-600 text-sm">正在处理中...</p>
                    </div>
                    
                    <!-- 结果区域 -->
                    <div id="date-result-container" class="hidden">
                        <div class="border-t border-gray-200 pt-6">
                            <h3 class="text-lg font-bold text-gray-800 mb-3">转换结果</h3>
                            <div class="bg-gray-50 rounded-md p-4 border border-gray-300">
                                <div class="flex justify-between items-center">
                                    <span id="timestamp-result" class="font-mono"></span>
                                    <button class="copy-btn text-gray-500 hover:text-blue-600" data-target="timestamp-result">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="mt-4">
                                <h4 class="font-medium text-gray-700 mb-2">其他格式</h4>
                                <div class="bg-gray-50 p-3 rounded border border-gray-200 text-sm">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                                        <div>
                                            <span class="text-gray-500">毫秒级时间戳:</span> 
                                            <span id="ms-timestamp-result" class="font-mono"></span>
                                        </div>
                                        <div>
                                            <span class="text-gray-500">ISO8601:</span> 
                                            <span id="date-iso-result" class="font-mono"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 关于时间戳的说明 -->
                <div class="border-t border-gray-200 mt-8 pt-6">
                    <h3 class="font-bold text-gray-800 mb-3">关于时间戳</h3>
                    <div class="bg-gray-50 p-4 rounded-md border border-gray-200">
                        <p class="mb-2">Unix时间戳是从1970年1月1日（UTC/GMT的午夜）开始所经过的秒数，不考虑闰秒。</p>
                        <p class="mb-2">常见的时间戳有两种：</p>
                        <ul class="list-disc pl-5 mb-2 space-y-1">
                            <li>秒级时间戳：精确到秒，通常是10位数字</li>
                            <li>毫秒级时间戳：精确到毫秒，通常是13位数字</li>
                        </ul>
                        <p>本工具支持在时间戳和各种日期格式之间进行转换，可以自定义日期格式。</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 消息提示模态框 -->
<div id="toast-container" class="fixed bottom-4 right-4 z-50"></div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const timestampToDateTab = document.getElementById('timestamp-to-date-tab');
        const dateToTimestampTab = document.getElementById('date-to-timestamp-tab');
        const timestampToDateContent = document.getElementById('timestamp-to-date');
        const dateToTimestampContent = document.getElementById('date-to-timestamp');
        
        const timestampFormat = document.getElementById('timestamp-format');
        const customTimestampFormatGroup = document.getElementById('custom-timestamp-format-group');
        const dateFormat = document.getElementById('date-format');
        const customDateFormatGroup = document.getElementById('custom-date-format-group');
        
        const timestampForm = document.getElementById('timestamp-form');
        const dateForm = document.getElementById('date-form');
        const currentTimestampBtn = document.getElementById('current-timestamp');
        const currentDateBtn = document.getElementById('current-date');
        
        const loadingIndicatorTimestamp = document.getElementById('loading-indicator-timestamp');
        const loadingIndicatorDate = document.getElementById('loading-indicator-date');
        const timestampResultContainer = document.getElementById('timestamp-result-container');
        const dateResultContainer = document.getElementById('date-result-container');
        
        // 切换标签页
        function switchToTimestampToDate() {
            timestampToDateTab.classList.add('text-purple-600', 'border-b-2', 'border-purple-600');
            timestampToDateTab.classList.remove('text-gray-500');
            dateToTimestampTab.classList.remove('text-purple-600', 'border-b-2', 'border-purple-600');
            dateToTimestampTab.classList.add('text-gray-500');
            
            timestampToDateContent.classList.remove('hidden');
            dateToTimestampContent.classList.add('hidden');
        }
        
        function switchToDateToTimestamp() {
            dateToTimestampTab.classList.add('text-purple-600', 'border-b-2', 'border-purple-600');
            dateToTimestampTab.classList.remove('text-gray-500');
            timestampToDateTab.classList.remove('text-purple-600', 'border-b-2', 'border-purple-600');
            timestampToDateTab.classList.add('text-gray-500');
            
            dateToTimestampContent.classList.remove('hidden');
            timestampToDateContent.classList.add('hidden');
        }
        
        timestampToDateTab.addEventListener('click', switchToTimestampToDate);
        dateToTimestampTab.addEventListener('click', switchToDateToTimestamp);
        
        // 格式选择器变化事件
        timestampFormat.addEventListener('change', function() {
            if (this.value === 'custom') {
                customTimestampFormatGroup.classList.remove('hidden');
            } else {
                customTimestampFormatGroup.classList.add('hidden');
            }
        });
        
        dateFormat.addEventListener('change', function() {
            if (this.value === 'custom') {
                customDateFormatGroup.classList.remove('hidden');
            } else {
                customDateFormatGroup.classList.add('hidden');
            }
        });
        
        // 获取当前时间戳
        currentTimestampBtn.addEventListener('click', function() {
            const now = Math.floor(Date.now() / 1000);
            document.getElementById('timestamp-input').value = now;
        });
        
        // 获取当前日期时间
        currentDateBtn.addEventListener('click', function() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            
            document.getElementById('date-input').value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        });
        
        // 时间戳转日期
        timestampForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            let timestampValue = document.getElementById('timestamp-input').value.trim();
            if (!timestampValue) {
                showMessage('请输入时间戳', 'error');
                return;
            }
            
            // 处理毫秒级时间戳
            if (timestampValue.length === 13) {
                timestampValue = Math.floor(timestampValue / 1000);
            }
            
            // 获取格式
            let format = timestampFormat.value;
            if (format === 'custom') {
                format = document.getElementById('custom-timestamp-format').value.trim();
                if (!format) {
                    showMessage('请输入自定义格式', 'error');
                    return;
                }
            }
            
            // 显示加载指示器
            loadingIndicatorTimestamp.classList.remove('hidden');
            timestampResultContainer.classList.add('hidden');
            
            // 发送请求
            fetch('/tools/dev/timestamp_converter', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    value: timestampValue,
                    type: 'to_date',
                    format: format
                })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errData => {
                        throw new Error(errData.message || '网络请求失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                // 隐藏加载指示器
                loadingIndicatorTimestamp.classList.add('hidden');
                
                if (data.error === 0) {
                    document.getElementById('date-result').textContent = data.result;
                    document.getElementById('iso-result').textContent = data.iso;
                    
                    // 生成本地时间和UTC时间
                    const date = new Date(timestampValue * 1000);
                    document.getElementById('local-time-result').textContent = date.toString();
                    document.getElementById('utc-time-result').textContent = date.toUTCString();
                    
                    timestampResultContainer.classList.remove('hidden');
                    showMessage('转换成功', 'success');
                } else {
                    showMessage('错误: ' + data.message, 'error');
                }
            })
            .catch(error => {
                // 隐藏加载指示器
                loadingIndicatorTimestamp.classList.add('hidden');
                showMessage('请求出错: ' + error.message, 'error');
            });
        });
        
        // 日期转时间戳
        dateForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const dateValue = document.getElementById('date-input').value.trim();
            if (!dateValue) {
                showMessage('请输入日期时间', 'error');
                return;
            }
            
            // 获取格式
            let format = dateFormat.value;
            if (format === 'custom') {
                format = document.getElementById('custom-date-format').value.trim();
                if (!format) {
                    showMessage('请输入自定义格式', 'error');
                    return;
                }
            }
            
            // 显示加载指示器
            loadingIndicatorDate.classList.remove('hidden');
            dateResultContainer.classList.add('hidden');
            
            // 发送请求
            fetch('/tools/dev/timestamp_converter', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    value: dateValue,
                    type: 'to_timestamp',
                    format: format
                })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errData => {
                        throw new Error(errData.message || '网络请求失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                // 隐藏加载指示器
                loadingIndicatorDate.classList.add('hidden');
                
                if (data.error === 0) {
                    document.getElementById('timestamp-result').textContent = data.result;
                    document.getElementById('ms-timestamp-result').textContent = data.result * 1000;
                    document.getElementById('date-iso-result').textContent = data.iso;
                    
                    dateResultContainer.classList.remove('hidden');
                    showMessage('转换成功', 'success');
                } else {
                    showMessage('错误: ' + data.message, 'error');
                }
            })
            .catch(error => {
                // 隐藏加载指示器
                loadingIndicatorDate.classList.add('hidden');
                showMessage('请求出错: ' + error.message, 'error');
            });
        });
        
        // 复制结果
        document.querySelectorAll('.copy-btn').forEach(button => {
            button.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target');
                const textToCopy = document.getElementById(targetId).textContent;
                
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(textToCopy)
                        .then(() => {
                            showMessage('已复制到剪贴板', 'success');
                        })
                        .catch(err => {
                            console.error('无法复制: ', err);
                            fallbackCopy(textToCopy);
                        });
                } else {
                    fallbackCopy(textToCopy);
                }
            });
        });
        
        // 复制回退方法
        function fallbackCopy(text) {
            const textarea = document.createElement('textarea');
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            
            try {
                document.execCommand('copy');
                showMessage('已复制到剪贴板', 'success');
            } catch (err) {
                console.error('回退复制失败:', err);
                showMessage('复制失败，请手动复制', 'error');
            }
            
            document.body.removeChild(textarea);
        }
        
        // 显示消息提示
        function showMessage(message, type = 'success') {
            const toast = document.createElement('div');
            
            toast.className = 'mb-3 px-4 py-2 rounded-md shadow-lg transform transition-opacity duration-500 ease-in-out opacity-0';
            
            if (type === 'error') {
                toast.classList.add('bg-red-500', 'text-white');
            } else {
                toast.classList.add('bg-green-500', 'text-white');
            }
            
            toast.textContent = message;
            
            document.getElementById('toast-container').appendChild(toast);
            
            // 淡入效果
            setTimeout(() => {
                toast.classList.remove('opacity-0');
                toast.classList.add('opacity-100');
            }, 10);
            
            // 3秒后淡出并移除
            setTimeout(() => {
                toast.classList.remove('opacity-100');
                toast.classList.add('opacity-0');
                setTimeout(() => {
                    if (toast.parentNode) {
                        toast.parentNode.removeChild(toast);
                    }
                }, 500);
            }, 3000);
        }
    });
</script>
{% endblock %} 